package com.weijia;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ControlPanel extends JPanel {
    private GameManager gameManager;
    private JTextArea articleArea;
    private JButton loadButton;
    private JLabel remainingLabel;
    private JProgressBar progressBar;
    private JLabel scoreLabel;
    private JTextArea errorStatsArea;
    private JTextField inputField;
    private JComboBox<TypingGamePlus.Difficulty> difficultyComboBox;
    private JButton startButton;
    private JButton pauseButton;
    private JButton restartButton;
    private JButton importButton;
    private JLabel highScoreLabel;
    private JButton resetHighScoreButton;
    private JButton endButton;

    public void setGameManager(GameManager gameManager) {
        this.gameManager = gameManager;
    }
    public ControlPanel() {
        setLayout(new BorderLayout(10, 10));
        setBackground(new Color(240, 245, 255));
        setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 文章输入区域
        JPanel articlePanel = new JPanel(new BorderLayout());
        articlePanel.setBorder(BorderFactory.createTitledBorder("文章输入"));
        articleArea = new JTextArea(8, 20);
        articleArea.setLineWrap(true);
        articleArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(articleArea);
        articlePanel.add(scrollPane, BorderLayout.CENTER);
        JPanel articleButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        loadButton = new JButton("加载文章");
        loadButton.setBackground(new Color(70, 130, 180));
        loadButton.setForeground(Color.WHITE);
        loadButton.setFocusPainted(false);
        loadButton.addActionListener(e -> loadArticle());
        articleButtonPanel.add(loadButton);
        importButton = new JButton("从文件导入");
        importButton.setBackground(new Color(100, 180, 220));
        importButton.setForeground(Color.WHITE);
        importButton.setFocusPainted(false);
        importButton.addActionListener(e -> importFromFile());
        articleButtonPanel.add(importButton);
        articlePanel.add(articleButtonPanel, BorderLayout.SOUTH);
        add(articlePanel, BorderLayout.NORTH);

        // 游戏设置面板（难度选择）
        JPanel settingsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        settingsPanel.setBorder(BorderFactory.createTitledBorder("游戏设置"));
        settingsPanel.add(new JLabel("难度选择:"));
        difficultyComboBox = new JComboBox<>(TypingGamePlus.Difficulty.values());
        difficultyComboBox.addActionListener(e -> {
            if (gameManager != null) {
                gameManager.setDifficulty((TypingGamePlus.Difficulty) difficultyComboBox.getSelectedItem());
            }
        });
        settingsPanel.add(difficultyComboBox);

        // 游戏状态面板
        JPanel statsPanel = new JPanel();
        statsPanel.setLayout(new GridLayout(6, 1, 10, 10));
        statsPanel.setBorder(BorderFactory.createTitledBorder("游戏状态"));
        JPanel highScorePanel = new JPanel(new BorderLayout());
        highScorePanel.add(new JLabel("最高分:"), BorderLayout.WEST);
        highScoreLabel = new JLabel("0");
        highScoreLabel.setFont(new Font("SansSerif", Font.BOLD, 16));
        highScoreLabel.setForeground(new Color(120, 60, 180));
        highScorePanel.add(highScoreLabel, BorderLayout.CENTER);
        resetHighScoreButton = new JButton("重置");
        resetHighScoreButton.setFont(new Font("SansSerif", Font.PLAIN, 12));
        resetHighScoreButton.setBackground(new Color(200, 80, 80));
        resetHighScoreButton.setForeground(Color.WHITE);
        resetHighScoreButton.setFocusPainted(false);
        resetHighScoreButton.addActionListener(e -> {
            if (gameManager != null) gameManager.resetHighScore();
        });
        highScorePanel.add(resetHighScoreButton, BorderLayout.EAST);
        statsPanel.add(highScorePanel);
        JPanel remainingPanel = new JPanel(new BorderLayout());
        remainingPanel.add(new JLabel("剩余单词:"), BorderLayout.WEST);
        remainingLabel = new JLabel("0");
        remainingLabel.setFont(new Font("SansSerif", Font.BOLD, 18));
        remainingLabel.setForeground(new Color(30, 120, 180));
        remainingPanel.add(remainingLabel, BorderLayout.CENTER);
        statsPanel.add(remainingPanel);
        JPanel progressPanel = new JPanel(new BorderLayout());
        progressPanel.add(new JLabel("完成进度:"), BorderLayout.WEST);
        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        progressPanel.add(progressBar, BorderLayout.CENTER);
        statsPanel.add(progressPanel);
        JPanel scorePanel = new JPanel(new BorderLayout());
        scorePanel.add(new JLabel("当前分数:"), BorderLayout.WEST);
        scoreLabel = new JLabel("0");
        scoreLabel.setFont(new Font("SansSerif", Font.BOLD, 18));
        scoreLabel.setForeground(new Color(220, 120, 0));
        scorePanel.add(scoreLabel, BorderLayout.CENTER);
        statsPanel.add(scorePanel);
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        startButton = new JButton("开始");
        startButton.setBackground(new Color(50, 180, 110));
        startButton.setForeground(Color.WHITE);
        startButton.setFocusPainted(false);
        startButton.addActionListener(e -> {
            if (gameManager != null) gameManager.startGame();
        });
        buttonPanel.add(startButton);
        pauseButton = new JButton("暂停");
        pauseButton.setBackground(new Color(220, 120, 0));
        pauseButton.setForeground(Color.WHITE);
        pauseButton.setFocusPainted(false);
        pauseButton.addActionListener(e -> {
            if (gameManager != null) {
                if (gameManager.isGameRunning()) {
                    if (gameManager.isGamePaused()) {
                        gameManager.resumeGame();
                    } else {
                        gameManager.pauseGame();
                    }
                }
            }
        });
        buttonPanel.add(pauseButton);
        restartButton = new JButton("重新开始");
        restartButton.setBackground(new Color(180, 50, 50));
        restartButton.setForeground(Color.WHITE);
        restartButton.setFocusPainted(false);
        restartButton.addActionListener(e -> {
            if (gameManager != null) gameManager.restartGame();
        });
        buttonPanel.add(restartButton);
        endButton = new JButton("结束游戏");
        endButton.setBackground(new Color(120, 120, 120));
        endButton.setForeground(Color.WHITE);
        endButton.setFocusPainted(false);
        endButton.addActionListener(e -> {
            if (gameManager != null) gameManager.endGameNow();
        });
        buttonPanel.add(endButton);
        statsPanel.add(buttonPanel);
        JPanel centerContainer = new JPanel(new BorderLayout());
        centerContainer.add(settingsPanel, BorderLayout.NORTH);
        centerContainer.add(statsPanel, BorderLayout.CENTER);
        add(centerContainer, BorderLayout.CENTER);

        // 错误统计 + 输入区域
        JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
        JPanel errorPanel = new JPanel(new BorderLayout());
        errorPanel.setBorder(BorderFactory.createTitledBorder("错误统计"));
        errorStatsArea = new JTextArea(5, 20);
        errorStatsArea.setEditable(false);
        errorStatsArea.setBackground(new Color(255, 240, 240));
        errorPanel.add(new JScrollPane(errorStatsArea), BorderLayout.CENTER);
        JPanel inputPanel = new JPanel(new BorderLayout(5, 5));
        inputPanel.add(new JLabel("输入单词:"), BorderLayout.WEST);
        inputField = new JTextField();
        inputField.addActionListener(e -> {
            if (gameManager != null) gameManager.processInput(inputField.getText().trim());
        });
        inputPanel.add(inputField, BorderLayout.CENTER);
        JButton submitButton = new JButton("提交");
        submitButton.setBackground(new Color(70, 130, 180));
        submitButton.setForeground(Color.WHITE);
        submitButton.addActionListener(e -> {
            if (gameManager != null) gameManager.processInput(inputField.getText().trim());
        });
        inputPanel.add(submitButton, BorderLayout.EAST);
        bottomPanel.add(errorPanel, BorderLayout.CENTER);
        bottomPanel.add(inputPanel, BorderLayout.SOUTH);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private void loadArticle() {
        String text = articleArea.getText().trim();
        if (text.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入英文文章！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        java.util.List<String> wordList = new java.util.ArrayList<>();
        String[] words = text.split("[\\s,.!?;:\"()]+");
        for (String word : words) {
            if (word.length() > 1) {
                wordList.add(word);
            }
        }
        if (gameManager != null) {
            gameManager.setWordList(wordList);
        }
        updateRemainingWords(wordList.size());
        JOptionPane.showMessageDialog(this, "成功加载 " + wordList.size() + " 个单词！", "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    private void importFromFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择文章文件");
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            java.io.File file = fileChooser.getSelectedFile();
            try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(file))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                articleArea.setText(sb.toString());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "读取文件失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 供 GameManager 调用的接口
    public void setArticleText(String text) {
        articleArea.setText(text);
    }
    public void updateScore(int score) {
        scoreLabel.setText(String.valueOf(score));
    }
    public void updateRemainingWords(int count) {
        remainingLabel.setText(String.valueOf(count));
    }
    public void updateProgress(int percent) {
        progressBar.setValue(percent);
    }
    public void updateErrorStats(String text) {
        errorStatsArea.setText(text);
    }
    public void updatePauseButtonText(String text) {
        pauseButton.setText(text);
    }
    public void setDifficulty(TypingGamePlus.Difficulty difficulty) {
        difficultyComboBox.setSelectedItem(difficulty);
    }
    public void clearInputField() {
        inputField.setText("");
    }
    public void updateHighScore(int score, String date) {
        if (date != null && !date.isEmpty()) {
            highScoreLabel.setText(score + "  (" + date + ")");
        } else {
            highScoreLabel.setText(String.valueOf(score));
        }
    }
    public String getArticleText() {
        return articleArea.getText();
    }
} 